<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span class="tag">渠道基本信息</span>
        <a-row v-if="title_ === '编辑'">
          <a-col :span="8" >
            <a-form-model-item label="渠道ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span>{{ model.channelNo }}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row justify="space-between" align="bottom">
          <a-col :span="8" >
            <a-form-model-item label="物流商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="providerId">
              <j-search-select-tag v-if="title_ === '新增'" @change="changeProvider" v-model="model.providerId" dict="hz_logistics_provider,name,id,logistics,is_enable='Y'" placeholder="请选择物流商" />
              <j-search-select-tag v-else @change="changeProvider" v-model="model.providerId" dict="hz_logistics_provider,name,id,logistics" placeholder="请选择物流商" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="渠道名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="channelName">
              <a-input v-model="model.channelName" placeholder="请输入渠道名称" ></a-input>
              <div class="has-error">
                <div class="ant-form-explain" v-if="validateMessage">{{ validateMessage }}</div>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="渠道代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="channelCode">
              <a-input v-model="model.channelCode" placeholder="请输入渠道代码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="面单来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="waybillSource">
              <j-dict-select-tag ref="dictSelectTagRef" type="radio" v-model="model.waybillSource" dictCode="logistics_waybill_source_type" placeholder="请选择面单来源" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="绑定仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseIds">
              <j-dict-select-tag type="list" v-model="model.warehouseIds" dictCode="logistics_shipping_warehouse" placeholder="请输入绑定仓库" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="申报币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currencyType">
              <j-dict-select-tag type="list" v-model="model.currencyType" dictCode="logistics_currency_type" placeholder="请选择申报币种" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="渠道描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="channelDesc">
              <a-textarea v-model="model.channelDesc" rows="4" :maxLength="50" placeholder="请输入渠道描述(最多50字)" />
            </a-form-model-item>
          </a-col>
          <a-divider/>
          <span class="tag">地址信息</span>
          <a-col :span="24" >
            <a-form-model-item label="地址信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="addressInfoId">
              <j-dict-select-tag type="list" @change="changeAddress" v-model="model.addressInfoId" dictCode="hz_logistics_address,name,id,logistics" placeholder="请选择地址信息" />
            </a-form-model-item>
          </a-col>
          <template v-if="model.addressInfoId">
            <a-col :span="24" >
              <a-form-model-item label="寄件人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <span>{{model.sender}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" >
              <a-form-model-item label="寄件地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <span>{{model.sendAddress}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" >
              <a-form-model-item label="发货地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <span>{{model.shipAddress}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" >
              <a-form-model-item label="退件地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <span>{{model.returnAddress}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" >
              <a-form-model-item label="揽收地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <span>{{model.collectAddress}}</span>
              </a-form-model-item>
            </a-col>
          </template>
          <a-divider/>
          <span class="tag">渠道货物类型</span>
          <!-- 子表单区域 -->
          <!-- <a-tabs v-model="activeKey" @change="handleChangeTabs">
            <a-tab-pane tab="物流货物类型" :key="refKeys[0]" :forceRender="true"> -->
              <j-editable-table
                :ref="refKeys[0]"
                :loading="logisticsGoodsTypeTable.loading"
                :columns="logisticsGoodsTypeTable.columns"
                :dataSource="logisticsGoodsTypeTable.dataSource"
                :maxHeight="300"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="true"
                :actionButton="true">
                <template v-slot:action="props">
                  <a-popconfirm title="确定删除吗？" @confirm="handleDL(props)">
                    <a>删除</a>
                  </a-popconfirm>
                </template>
              </j-editable-table>
            <!-- </a-tab-pane>
          </a-tabs> -->
          <a-divider v-if="providerType" />
          <span class="tag" v-if="providerType" >渠道配置</span>
          <a-col :span="24" v-if="providerType =='YUN_TU'" >
            <a-form-model-item  label="是否将运单号作为跟踪号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="YUN_TU-isWayBill-Ref" type="list" v-model="configJson.isWayBill" dictCode="y_n" placeholder="请选择是否" disabled />
            </a-form-model-item>
            <a-form-model-item  label="预报订单的单号类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="YUN_TU-orderNoType-Ref" type="list" v-model="configJson.orderNoType" dictCode="logistics_order_no_type" placeholder="请选择预报单号类型" />
            </a-form-model-item>
            <a-form-model-item  label="增值税" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="YUN_TU-valueAddedTaxNo-Ref" type="list" v-model="configJson.valueAddedTaxNo" dictCode="logistics_value_added_tax" placeholder="请选择增值税号" />
            </a-form-model-item>
            <a-form-model-item  label="IOSS税号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="YUN_TU-iossTaxNo-Ref" type="list" v-model="configJson.iossTaxNo" dictCode="logistics_ioss_tax" placeholder="请选择IOSS税号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="providerType =='HUA_HAN'" >
            <a-form-model-item  label="卖家税号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="HUA_HAN-valueAddedTaxNo-Ref" type="list" v-model="configJson.valueAddedTaxNo" dictCode="logistics_value_added_tax" placeholder="请选择卖家税号" />
            </a-form-model-item>
            <a-form-model-item  label="打印面单尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="HUA_HAN-waybillSize-Ref" type="list" v-model="configJson.waybillSize" dictCode="logistics_waybill_size" placeholder="打印面单尺寸" />
            </a-form-model-item>
            <a-form-model-item  label="标签类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="HUA_HAN-tagType-Ref" type="list" v-model="configJson.tagType" dictCode="logistics_tag_type" placeholder="请选择标签类型" />
            </a-form-model-item>
            <a-form-model-item  label="包裹申报种类" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="HUA_HAN-packageType-Ref" type="list" v-model="configJson.packageType" dictCode="logistics_package_type" placeholder="请选择包裹申报种类" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="providerType =='YAN_WEN'" >
            <a-form-model-item  label="物品类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="YAN_WEN-packageType-Ref" type="list" v-model="configJson.packageType" dictCode="logistics_package_type" placeholder="请选择物品类型" />
            </a-form-model-item>
            <a-form-model-item  label="打印面单尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="YAN_WEN-waybillSize-Ref" type="list" v-model="configJson.waybillSize" dictCode="logistics_waybill_size" placeholder="打印面单尺寸" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="providerType =='DI_YI'" >
            <a-form-model-item label="卖家税号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="DI_YI-valueAddedTaxNo-Ref" type="list" v-model="configJson.valueAddedTaxNo" dictCode="logistics_value_added_tax" placeholder="请选择卖家税号" />
            </a-form-model-item>
            <a-form-model-item  label="打印面单尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="DI_YI-waybillSize-Ref" type="list" v-model="configJson.waybillSize" dictCode="logistics_waybill_size" placeholder="打印面单尺寸" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="providerType =='TONG_YOU'" >
            <a-form-model-item  label="物品类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="TONG_YOU-packageType-Ref" type="list" v-model="configJson.packageType" dictCode="logistics_package_type" placeholder="物品类型" />
            </a-form-model-item>
            <a-form-model-item  label="打印面单尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="TONG_YOU-waybillSize-Ref" type="list" v-model="configJson.waybillSize" dictCode="logistics_waybill_size" placeholder="打印面单尺寸" />
            </a-form-model-item>
            <a-form-model-item  label="物流编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model.trim="configJson.logisticsCode" placeholder="请输入物流编码" />
            </a-form-model-item>
            <a-form-model-item  label="增值税纳税人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag ref="TONG_YOU-valueAddedTaxNo-Ref" type="list" v-model="configJson.valueAddedTaxNo" dictCode="logistics_value_added_tax" placeholder="请选择增值税" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>

  </a-spin>
</template>

<script>

  import { getAction, httpAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'LogisticsChannelForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{},
        configJson: {},
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           providerId: [
              { required: true, message: '请输入物流商!'},
           ],
           channelName: [
              { required: true, message: '请输入渠道名称!'},
           ],
           channelCode: [
              { required: true, message: '请输入渠道代码!'},
           ],
           waybillSource: [
              { required: true, message: '请输入面单来源!'},
           ],
           warehouseIds: [
              { required: true, message: '请输入绑定仓库!'},
           ],
           currencyType: [
              { required: true, message: '请输入申报币种!'},
           ],
           addressInfoId: [
              { required: true, message: '请选择地址信息!' }
           ]
        },
        refKeys: ['logisticsGoodsType', ],
        tableKeys:['logisticsGoodsType', ],
        activeKey: 'logisticsGoodsType',
        // 物流货物类型
        logisticsGoodsTypeTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '货物类型代码',
              key: 'goodsCode',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '货物类型名称',
              key: 'name',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '物流商货物类型代码',
              key: 'providerGoodsCode',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '操作',
              key: 'action',
              width: '8%',
              type: FormTypes.slot, // 定义该列为 自定义插值列
              slotName: 'action' // slot 的名称，对应 v-slot 冒号后面和等号前面的内容
            }
          ]
        },
        addressAll: {},
        providerAll: {},
        providerType: '',
        yuntuConfig: {},
        yanwenConfig: {},
        diyiConfig: {},
        url: {
          add: "/logistics/channel/add",
          edit: "/logistics/channel/edit",
          queryById: "/logistics/channel/queryById",
          getAllAddressInfo: "/logistics/address/logisticsAddress/all",
          getAllProviderInfo: "/logistics/logisticsProvider/list",
          logisticsGoodsType: {
            list: '/logistics/channel/queryLogisticsGoodsTypeByMainId'
          },
        },
        validateMessage: ''
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      title_: {
        type: String,
        default: ''
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    watch: {
      'model.channelName': {
        handler(val){
          this.validateMessage = '';
        }
      }
    },
    created () {
    },
    methods: {
      test(){
        console.log(JSON.stringify(this.model));
      },
      addBefore(){
        this.logisticsGoodsTypeTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      initAddressInfo(){
        getAction(this.url.getAllAddressInfo, {}).then((res) => {
          if(res.success){
            if(res.result){
              res.result.forEach((item) => {
                this.addressAll[item.id] = item;
              });
              if(this.model.addressInfoId){
                this.changeAddress(this.model.addressInfoId);
              }
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      initProviderInfo(){
        let params = {
          column: 'createTime',
          order: 'desc',
          pageNo: 1,
          pageSize: 999
        };
        if(this.title_ === '新增'){
          params.isEnable = 'Y';
        }
        getAction(this.url.getAllProviderInfo, params).then((res) => {
          if(res.success){
            if(res.result && res.result.records){
              res.result.records.forEach((item) => {
                this.providerAll[item.id] = item;
              });
              if(this.model.providerId){
                this.changeProvider(this.model.providerId);
              }
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      changeAddress(addressId){
        if(!(this.addressAll && this.addressAll[addressId])) return;
        this.$set(this.model, 'sender', this.addressAll[addressId].sender || "");
        this.$set(this.model, 'sendAddress', this.addressAll[addressId].sendAddress || "");
        this.$set(this.model, 'shipAddress', this.addressAll[addressId].shipAddress || "");
        this.$set(this.model, 'returnAddress', this.addressAll[addressId].returnAddress || "");
        this.$set(this.model, 'collectAddress', this.addressAll[addressId].collectAddress || "");
      },
      changeProvider(providerId){
        this.providerType = (this.providerAll && this.providerAll[providerId] && this.providerAll[providerId].type) || "";
        //新增，默认展示实现
        if(this.model.id) return;
        this.configJson = {};
        let providerTypeList = [
          {
            type: 'YUN_TU',
            valueList: [
              {
                value: 'isWayBill',
                index: 0
              },
              {
                value: 'orderNoType',
                index: 0
              },
              {
                value: 'valueAddedTaxNo',
                index: 0
              },
              {
                value: 'iossTaxNo',
                index: 0
              },
            ]
          },
          {
            type: 'HUA_HAN',
            valueList: [
              {
                value: 'valueAddedTaxNo',
                index: 0
              },
              {
                value: 'waybillSize',
                index: 0
              },
              {
                value: 'tagType',
                index: 0
              },
              {
                value: 'packageType',
                index: 0
              },
            ]
          },
          {
            type: 'YAN_WEN',
            valueList: [
              {
                value: 'packageType',
                index: 'last'
              },
              {
                value: 'waybillSize',
                index: 0
              },
            ]
          },
          {
            type: 'DI_YI',
            valueList: [
              {
                value: 'valueAddedTaxNo',
                index: 0
              },
              {
                value: 'waybillSize',
                index: 0
              },
            ]
          },
          {
            type: 'TONG_YOU',
            valueList: [
              {
                value: 'packageType',
                index: 'last'
              },
              {
                value: 'waybillSize',
                index: 0
              },
              {
                value: 'valueAddedTaxNo',
                index: 0
              },
            ]
          },
        ];

        this.$nextTick(() => {
          providerTypeList.forEach(item => {
            item.valueList.forEach(childItem => {
              let refKey = `${item.type}-${childItem.value}-Ref`;
              if(this.$refs[refKey]){
                let dictOptions = this.$refs[refKey].getCurrentDictOptions();
                childItem.index = childItem.index === 'last' ? (dictOptions.length - 1) : childItem.index;
                this.$set(this.configJson, childItem.value, (dictOptions && dictOptions[`${childItem.index}`] && dictOptions[`${childItem.index}`].value) || '');
              }
            })
          })
        })
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 地址初始化及回显
        this.initAddressInfo();
        // 物流商初始化及回显
        this.initProviderInfo();
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.logisticsGoodsType.list, params, this.logisticsGoodsTypeTable)
        }
        this.configJson = (this.model && this.model.configJson) ? Object.assign({}, this.model.configJson) : {};
        //新增页面面单来源赋值
        if(this.model.id ) return;
        this.$nextTick(() => {
          if(this.$refs.dictSelectTagRef){
            let dictOptions = this.$refs.dictSelectTagRef.getCurrentDictOptions();
            this.$set(this.model, 'waybillSource', (dictOptions && dictOptions[0] && dictOptions[0].value) || '');
          }
        })
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues){
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          logisticsGoodsTypeList: allValues.tablesValue[0].values,
          configJson: this.configJson
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      handleDL(props) {
        // 使用实例：删除当前操作的行
        let { rowId, target } = props;
        target.removeRows(rowId);
      },
    }
  }
</script>

<style scoped>
.tag{
  border: 1px solid #1890FF;
  padding: 2px 10px;
  border-radius: 6px;
  color: #1890FF;
  margin-bottom: 4px;
  display: inline-block;
}
/deep/.vxe-table--empty-placeholder{
  height: auto !important;
}
/deep/.vxe-table--body-wrapper{
  height: auto !important;
}
</style>